//
//  FSHomePageVC.m
//  FieldStory
//
//  Created by itte on 2017/6/21.
//  Copyright © 2017年 funmain. All rights reserved.
//

#import "FSHomePageVC.h"
#import "FSLoginVC.h"
#import "CategoryCltCell.h"

@interface FSHomePageVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIActionSheetDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lcsImgHeight;
@property (weak, nonatomic) IBOutlet UIView *contentView;
@property (weak, nonatomic) IBOutlet UICollectionView *cltView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lcsTopImage;
@property (assign, nonatomic) CGFloat lastPosition;
@property (weak, nonatomic) IBOutlet UIButton *btnStart;
@property (strong, nonatomic) NSMutableArray *dataArray;

@end

@implementation FSHomePageVC

- (void)viewDidLoad {
    [super viewDidLoad];

    // 隐藏水平滚动条
    self.cltView.showsHorizontalScrollIndicator = NO;
    [self.cltView registerNib:[UINib nibWithNibName:@"CategoryCltCell" bundle:nil] forCellWithReuseIdentifier:@"CategoryCltCellID"];
    self.cltView.delegate = self;
    self.cltView.dataSource = self;
    self.lastPosition = 0;
    self.btnStart.layer.cornerRadius = 17.5f;
    [self getMyFarmer];
    addNObserver(@selector(getMyFarmer), kNotificationLoginSuccess);
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

-(void)dealloc
{
    removeNObserver(kNotificationLoginSuccess);
}

-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark - 网络请求
// 获取农场信息
-(void)getMyFarmer
{
    if (![FSLogin sharedInstance].isLogined) {
        return ;
    }
    // WeakSelfType blockSelf = self;
    [[AFNetworkManager sharedInstance] httpGetWithUrl:KGetFarmsInfo params:nil showHUD:NO toShowHUDView:nil success:^(id responseObject, NSString *errorMessage) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
        }
    } fail:^(NSString *errorCode, NSString *errorMessage) {
        
    }];
}

-(void)getRYInfo
{
    if (![FSLogin sharedInstance].isLogined) {
        return ;
    }
    WeakSelfType blockSelf = self;
    [[AFNetworkManager sharedInstance] httpGetWithUrl:KGetHomeInfo params:nil showHUD:NO toShowHUDView:nil success:^(id responseObject, NSString *errorMessage) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSArray *data = [FSHomeModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"usergoods"]];
            [blockSelf.dataArray removeAllObjects];
            [blockSelf.dataArray addObjectsFromArray:data];
            [blockSelf.cltView reloadData];
        }
    } fail:^(NSString *errorCode, NSString *errorMessage) {
        
    }];
}

-(void)modifyFarmerName:(NSString *)name
{
    WeakSelfType blockSelf = self;
    [[AFNetworkManager sharedInstance] httpPostWithUrl:@"farm/setName" params:@{@"farm_name":name} showHUD:YES toShowHUDView:self.view success:^(id responseObject, NSString *errorMessage) {
        [MBProgressHUD showInformation:@"修改成功" toView:blockSelf.view andAfterDelay:1.0];
    } fail:^(NSString *errorCode, NSString *errorMessage) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"修改农场名称失败" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }];
}

#pragma mark - 按钮点击事件
- (IBAction)btnChoiseClick
{
    if(![FSLogin sharedInstance].isLogined){
        [self presentViewcontroller:@"FSLoginVC" animated:YES];
        return ;
    }
    UIActionSheet *imgActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"农场改名",@"联系管家", nil];
    [imgActionSheet showInView:self.view];
}
// 开始认养
- (IBAction)btnStartClick
{
    if(![FSLogin sharedInstance].isLogined){
        [self presentViewcontroller:@"FSLoginVC" animated:YES];
        return ;
    }
    [self pushViewController:@"FSCategoryVC"];
}

#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > 50.f) {
        NSLog(@"-- scroll up --");
        _lastPosition = offsetY;
        [self imageMoveUp:-250];
    }
    else if(offsetY < -50){
        NSLog(@"-- scroll down --");
        _lastPosition = offsetY;
        [self imageMoveUp:0];
    }
}

-(void)imageMoveUp:(CGFloat)distance
{
    if (distance < -250) {
        return ;
    }
    [UIView animateWithDuration:3 animations:^{
        _lcsTopImage.constant = distance;
    }];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section;
{
    return self.dataArray.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CategoryCltCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CategoryCltCellID" forIndexPath:indexPath];
    FSHomeModel *homeInfo = self.dataArray[indexPath.row];
    NSURL *imgUrl = [NSURL URLWithString:homeInfo.images];
    [cell.imgProduct sd_setImageWithURL:imgUrl placeholderImage:[UIImage imageNamed:@"icon_wx"]];
    cell.lbName.text = homeInfo.name;
    cell.layer.borderColor = [UIColor groupTableViewBackgroundColor].CGColor;
    cell.layer.borderWidth = 0.6f;
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(SCREEN_WIDTH/3, SCREEN_WIDTH/3+20);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"-- %ld --",indexPath.row);
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
}

#pragma mark - UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex)
    {
        NSLog(@"取消");
    }
    switch (buttonIndex) {
        case 0:
        {
            NSLog(@"农场改名");
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"修改农场名称" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
            UITextField *txtName = [alert textFieldAtIndex:0];
            txtName.keyboardType = UIKeyboardTypeDefault;
            [alert show];
        }
        break;
        case 1:
            [@"" callPhone];
            break;
        default:
            break;
    }
}


#pragma mark - UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        UITextField *txt = [alertView textFieldAtIndex:0];
        NSString *value = txt.text.trimString;
        [self modifyFarmerName:value];
    }
}
@end
